package com.mw.controller;

import com.hankcs.hanlp.HanLP;
import com.mw.domain.News;
import com.mw.domain.User;
import com.mw.service.CommentService;
import com.mw.service.NewsService;
import com.mw.util.Spider;
import com.mw.util.StringTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping()
public class EditController {
    @Autowired
    NewsService newsService;
    @Autowired
    CommentService commentService;

    int PAGENUMBER = 0;//记录当前页面
    /**
     * 管理员权限审核，所用方法都要加
     * @param
     * @return
     */
    public boolean isAdmin(HttpSession httpSession){
        if(httpSession.getAttribute("user")==null){

        }else{
            User user = (User)httpSession.getAttribute("user");
            if(user.getUsername().equals("admin"))
                return true;
        }
        return false;
    }

    /**
     * 进入编辑页，显示数据
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/edit")
    public String toEditPage(@RequestParam(value = "pageNumber",required = false)String pageNumber, HttpSession httpSession, ModelMap map){
        if(isAdmin(httpSession)){
            if(pageNumber==null ||"".equals(pageNumber)){
                pageNumber="0";
            }
            int pageNum = Integer.parseInt(pageNumber);
            List<News> editNews = null;
            Page<News> newsPage = null;
            if(httpSession.getAttribute("switch")==null) {
                newsPage = newsService.getAllNewsTypeIsNull(pageNum,10);
                editNews = newsPage.getContent();
                //抓关键字
                for(int i=0;i<editNews.size();i++){
                    String content = "";//储存标题和无图正文
                    Pattern txtPattern = Pattern.compile("[\\u4e00-\\u9fa5]");//中文字符
                    Matcher txtMatcher = txtPattern.matcher(editNews.get(i).getContext());
                    content += editNews.get(i).getTitle();
                    while(txtMatcher.find()){
                        content += txtMatcher.group(0);
                    }
                    //System.out.println(content);
                    List<String> keywordList = HanLP.extractKeyword(content,4);//HandLP工具包，找关键词
                    StringTool stringTool = new StringTool();
                    String smh = stringTool.getShuMingHao(editNews.get(i).getTitle());//标题《》基本上是关键字，特殊处理
                    if(!("".equals(smh))){
                        keywordList.add(smh);
                    }
                    String keyword = StringUtils.collectionToDelimitedString(keywordList,",");//List转化为以逗号分隔的字符串
                    editNews.get(i).setType(keyword);
                }
            }else {
                newsPage = newsService.getAllNewsTypeIsNotNull(pageNum,10);
                editNews = newsPage.getContent();
            }
            PAGENUMBER = pageNum;
            map.addAttribute("editNews", editNews);
            map.addAttribute("newsCount",newsPage.getTotalElements());
            map.addAttribute("totalPages",newsPage.getTotalPages()-1);
            map.addAttribute("isFirstPage",newsPage.isFirst());
            map.addAttribute("isLastPage",newsPage.isLast());
            map.addAttribute("pageNum",pageNum);
            return "edit";
        }
        return "error";
    }

    /**
     * 切换审核还是编辑
     * @param
     * @return
     */
    @RequestMapping(value = "edit/switch",method = RequestMethod.GET)
    public String switchPage(HttpSession httpSession){
        if(isAdmin(httpSession)){
            if(httpSession.getAttribute("switch")!=null) {
                httpSession.setAttribute("switch",null);
            }else {
                httpSession.setAttribute("switch", "不为空");
            }
            return "redirect:/edit";
        }
        return "error";
    }

    /**
     * 爬取新闻进入待审核状态
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "edit/getnews",method = RequestMethod.GET)
    public String getNews(HttpSession httpSession,ModelMap map){
        if(isAdmin(httpSession)) {
            // 定义即将访问的链接
            String url = "http://www.huabian.com/";
            // 访问链接并获取页面内容
            String content = Spider.SendGet(url);
            // 获取该页面的所有的新闻对象
            ArrayList<News> newNews = Spider.GetNews(content);
            // 打印结果
            //System.out.println(newNews);
            int count = 0;//记录抓取了多少条新数据
            for(int i=0;i<newNews.size();i++){
                count+=newsService.saveDifferentNews(newNews.get(i));
            }
            map.addAttribute("getCount",count);
            return "redirect:/edit/";
        }
        return "error";
    }

    /**
     * 对新闻设置类型（表示发布），或删除该id的新闻
     * @param id 新闻id
     * @param type 新闻类型
     * @param
     * @return
     */
    @RequestMapping(value = "edit/{id}",method = RequestMethod.GET)
    public String checkNews(@PathVariable("id") Integer id, String type, HttpSession httpSession){
        if(isAdmin(httpSession)){
            News news = newsService.getNewsById(id);
            if(type.startsWith("删除")){
                newsService.delNews(news);
                commentService.delAllbyNid(id.toString());
            }else {
                news.setType(type);
                newsService.updateNews(news);
            }
            return "redirect:/edit?pageNumber=" + PAGENUMBER;
        }
        return "error";
    }
}
